<template>
  <div ref="dom" class="charts chart-bar" style="width:100%;height:calc(100% - 30px)"></div>
</template>
<script>
import echarts from 'echarts'
import tdTheme from './theme.json'
import {off, on} from '@/libs/tools'

echarts.registerTheme('tdTheme', tdTheme)
export default {
  name: 'ChartBar',
  props: {
    value: Object,
    colorA: Array
  },
  data() {
    return {
      dom: null
    }
  },
  methods: {
    resize() {
      this.dom.resize()
    }
  },
  mounted() {
    this.$nextTick(() => {
      let _this = this;
      let xAxisData = Object.keys(this.value)
      let seriesData = Object.values(this.value)
      let option = {
        color: ['#4598e5'],
        title: {
          x: 'center'
        },
        grid: {
          top: 15,
          bottom: 20,
          left: 40,
          right: 15
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          splitLine: {
            show: false,
            position: 'top'
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: false,
            position: 'top'
          }
        },
        series: [{
          data: seriesData,
          type: 'bar',
          barMaxWidth: 60,
          label: {
            normal: {
              show: true,
              position: 'top',
              fontSize: 16,
              color: '#fff',
              offset: [2, -2]
            }
          }
        }]
      }
      if (this.colorA && this.colorA.length) {
        option.series[0].itemStyle = {
          normal: {
            color: function (params) {
              var colorList = _this.colorA;
              return colorList[params.dataIndex]
            }
          }
        }
      }
      this.dom = echarts.init(this.$refs.dom, 'tdTheme')
      this.dom.setOption(option)
      on(window, 'resize', this.resize)
    })
  },
  beforeDestroy() {
    off(window, 'resize', this.resize)
  }
}
</script>
